<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use app\portal\model\PortalCategoryPostModel;
use app\portal\model\PortalTagPostModel;
use app\portal\model\RecycleBinModel;
use cmf\controller\AdminBaseController;
use app\admin\model\ChannelFieldModel;
use app\portal\model\PortalPostModel;
use app\portal\service\PostService;
use app\portal\model\PortalCategoryModel;
use app\admin\model\ThemeModel;
use think\Facade\Db;

class AdminArticleController extends AdminBaseController
{
    /**
     * 文章列表
     * @adminMenu(
     *     'name'   => '文章管理',
     *     'parent' => 'portal/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章列表',
     *     'param'  => ''
     * )
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $param = $this->request->param();
        $categoryId = $this->request->param('category', 0, 'intval');
        $postService = new PostService();
        $PortalPostModel = new PortalPostModel();
        $PortalCategoryModel = new PortalCategoryModel();
        if (isset($param['cid'])) {
            $categoryId = $param['cid'];
            $param['category'] = $param['cid'];
        }
        $data        = $postService->adminArticleList($param);
        $CategoryOne = $PortalCategoryModel->CategoryOne($categoryId);
        $data->appends($param);
        $categoryTree        = $PortalCategoryModel->adminCategoryTree($categoryId);
        $tpl = $PortalPostModel->strModel($CategoryOne['list_tpl']);
        $this->assign('start_time', isset($param['start_time']) ? $param['start_time'] : '');
        $this->assign('end_time', isset($param['end_time']) ? $param['end_time'] : '');
        $this->assign('keyword', isset($param['keyword']) ? $param['keyword'] : '');
        $this->assign('articles', $data->items());
        $this->assign('category_tree', $categoryTree);
        $this->assign('category', $categoryId);
        $this->assign('TplOne', $tpl);
        $this->assign('page', $data->render());


        return $this->fetch();
    }

    /**
     * 添加文章
     * @adminMenu(
     *     'name'   => '添加文章',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加文章',
     *     'param'  => ''
     * )
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add()
    {
        $content = hook_one('portal_admin_article_add_view');

        if (!empty($content)) {
            return $content;
        }

        $themeModel        = new ThemeModel();
        $articleThemeFiles = $themeModel->getActionThemeFiles('portal/Article/index');
        $this->assign('article_theme_files', $articleThemeFiles);
        return $this->fetch();
    }

    /**
     * 添加文章提交
     * @adminMenu(
     *     'name'   => '添加文章提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加文章提交',
     *     'param'  => ''
     * )
     */
    public function addPost()
    {
        if ($this->request->isPost()) {
            $data   = $this->request->param();
            $portalPostModel = new PortalPostModel();
            $PortalCategoryModel = new PortalCategoryModel();
            unset($data['post']['id']);
            $data['post']['post_status'] = 1;
            $data['post']['is_top'] = 0;
            $data['post']['recommended'] = 0;
            $post   = $data['post'];
            $data['catpost'] = isset($data['catpost']) ? $data['catpost'] : [];
            $catpost = $data['catpost'];
            $result = $this->validate($post,'AdminArticle');
            if ($result !== true) {
                $this->error($result);
            }
            $row = $PortalCategoryModel->where("id=".$post['categories'])->find();
            $field_where = [
                ["cat_id","like","%".$row['id']."%"],
                ['dtype',"like","img%"],
            ];
            $imgs = Db::name('channel_field')->where($field_where)->select();
            if (count($imgs)>0) {
                if (count($imgs) > 1) {
                    foreach ($imgs as $key => $value) {
                        if (isset($catpost[$value['name']])) {
                            if (is_array($catpost[$value['name']])) {
                                foreach ($catpost[$value['name']] as $k => $url) {
                                    $photoUrl = cmf_asset_relative_url($url);
                                    $catpost['s'][$value['name']][] = $photoUrl;
                                }
                                $data['catpost'][$value['name']] = json_encode($catpost['s'][$value['name']]);
                            }else{
                                $photoUrl = cmf_asset_relative_url($catpost[$value['name']]);
                                $data[$value['name']] = $photoUrl;
                            }
                            
                        }else{
                            $data['catpost'][$value['name']] = '';
                        }
                    }
                    
                }else{
                    if (isset($catpost[$imgs[0]['name']]) and !empty($catpost[$imgs[0]['name']])) {
                        if (is_array($catpost[$imgs[0]['name']])) {
                            foreach ($catpost[$imgs[0]['name']] as $key => $url) {
                                $photoUrl = cmf_asset_relative_url($url);
                                $catpost[$imgs[0]['name']][$key] = $photoUrl;
                            }
                            $data['catpost'][$imgs[0]['name']] = json_encode($catpost[$imgs[0]['name']]);
                        }else{
                            $photoUrl = cmf_asset_relative_url($catpost[$imgs[0]['name']]);
                            $data[$imgs[0]['name']] = $photoUrl;
                        }
                        
                    }else{
                        $data['catpost'][$imgs[0]['name']] = '';
                    }
                }
            }

            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $post['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($post['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }

            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $post['more']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($post['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }
            
            $row = $PortalCategoryModel->where("id=".$post['categories'])->find();
            $row2 = $PortalCategoryModel->where("id=".$row['parent_id'])->find();
            if (!empty($row2)) {
               $data['post']['parent_id'] = $row2['id'];
            }
            $portalPostModel->adminAddArticle($data, $post['categories']);
            $data['post']['id'] = $portalPostModel->id;
            
            $temlname = explode('_', $row['list_tpl']);
            if (isset($temlname[1]) && strncmp((string)$temlname[1],"single",7) == 0){
                $strname = $temlname[1].'_add';
            }else{
                $strname = $temlname[1].'_edit';
            }
            if (!empty($portalPostModel->id)) {
                $this->success('添加成功!', url('AdminArticle/'.$strname, ['id' => $portalPostModel->id,'cid'=>$row['id']]));
            }else{
                $this->error('添加失败！');
            }
        }
    }

    /**
     *单页模板
     */
    public function single_add(){

        $data = $this->request->param();

        $PortalCategoryModel = new PortalCategoryModel();
        $ChannelFieldModel = new ChannelFieldModel();
        $PortalPostModel = new PortalPostModel();
        if (!isset($data['cid'])) {
            $data['cid'] = 0;
        }else{
            $this->assign('cid', $data['cid']);
        }
        $post = $PortalCategoryModel->find($data['cid']);
        $fields = $ChannelFieldModel->where('status',1)->field('id,name,channel_id,dtype,cat_id,title')->select();
        $single = $PortalPostModel->alias('a')->join('portal_category_post b','a.id = b.post_id')->where('b.category_id',$data['cid'])->find();
        if (!empty($single)) {
            $aedd = 'editPost';
        }else{
            $aedd = 'addPost';
        }
        if (!isset($single['published_time'])) 
            $single['published_time'] = time();
        
        $this->assign('post', $single);
        $this->assign('aedd', $aedd);
        $this->assign('single', $single);
        $this->assign('fields', $fields);

        $themeModel        = new ThemeModel();
        $articleThemeFiles = $themeModel->getActionThemeFiles('portal/Article/index');
        $this->assign('article_theme_files', $articleThemeFiles);
        return $this->fetch('admin_article/single_add');
          
    }

    //请求模板
    public function ajax_get_field(){

        $data = $this->request->param();
        $ChannelFieldModel = new ChannelFieldModel();
        $PortalPostModel = new PortalPostModel();
        if ($this->request->isAjax() && $data['_ajax'] == 1) {
            if ($data['article_id'] != '') {
                $post = $PortalPostModel
                    ->alias('a')
                    ->where('a.id',$data['article_id'])
                    ->join('cmm_portal_category_post b','a.id = b.post_id')
                    ->find();
            }else{
                $post = [];
            }
            $fields = $ChannelFieldModel->where('status',1)->field('id,name,channel_id,dtype,cat_id,title,dfvalue')->select();
            $arr = [];
            foreach ($fields as $key => $value) {
                if (strstr($value['cat_id'], $data['cid'])) {
                    $arr[] = $value;
                }
            }
            $this->assign('post', $post);
            $this->assign('fields', $arr);
            $html = $this->fetch('admin_article/field');
            $this->successful('请求成功',$html);
        }
    }

     /**
     * 添加文章
     * @adminMenu(
     *     'name'   => '添加文章',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加文章',
     *     'param'  => ''
     * )
     */
    public function article_add()
    {
        $where = $this->request->param();
 
        $PortalCategoryModel = new PortalCategoryModel();
        $ChannelFieldModel = new ChannelFieldModel();
        if (!isset($where['cid'])) {
            $where['cid'] = 0;
        }else{
            $this->assign('cid', $where['cid']);
        }
        $cat = $PortalCategoryModel->where('id',$where['cid'])->find();
        $fields = $ChannelFieldModel->where('status',1)->field('id,name,channel_id,dtype,cat_id,title')->select();

        $this->assign('cat', $cat);
        $this->assign('fields', $fields);

        $themeModel        = new ThemeModel();
        $articleThemeFiles = $themeModel->getActionThemeFiles('portal/Article/index');
        $this->assign('article_theme_files', $articleThemeFiles);
        return $this->fetch('admin_article/article_add');
    }

    /**
     * 编辑文章
     * @adminMenu(
     *     'name'   => '编辑文章',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑文章',
     *     'param'  => ''
     * )
     */
    public function article_edit()
    {
        $where = $this->request->param();
        if (!isset($where['cid'])) {
            $where['cid'] = 0;
        }
        $portalPostModel = new PortalPostModel();
        $post            = $portalPostModel
                            ->alias('a')
                            ->join('cmm_portal_category_post b','a.id = b.post_id')
                            ->where('a.id',$where['id'])
                            ->find();
        $catpost = $portalPostModel->where('id', $where['id'])->find();
        $postCategories  = $catpost->categories()->alias('a')->column('a.name', 'a.id');
        $postCategoryIds = implode(',', array_keys($postCategories));
        $themeModel        = new ThemeModel();
        $articleThemeFiles = $themeModel->getActionThemeFiles('portal/Article/index');
        $this->assign('article_theme_files', $articleThemeFiles);

        $this->assign('post', $post);
        $this->assign('cid', $where['cid']);
        $this->assign('post_categories', $postCategories);
        $this->assign('post_category_ids', $postCategoryIds);
        return $this->fetch('admin_article/article_edit');
    }   

    /**
     * 编辑文章
     * @adminMenu(
     *     'name'   => '编辑文章',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑文章',
     *     'param'  => ''
     * )
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        $content = hook_one('portal_admin_article_edit_view');

        if (!empty($content)) {
            return $content;
        }

        $id = $this->request->param('id', 0, 'intval');

        $portalPostModel = new PortalPostModel();
        $post            = $portalPostModel->where('id', $id)->find();
        $postCategories  = $post->categories()->alias('a')->column('a.name', 'a.id');
        $postCategoryIds = implode(',', array_keys($postCategories));

        $themeModel        = new ThemeModel();
        $articleThemeFiles = $themeModel->getActionThemeFiles('portal/Article/index');
        $this->assign('article_theme_files', $articleThemeFiles);
        $this->assign('post', $post);
        $this->assign('post_categories', $postCategories);
        $this->assign('post_category_ids', $postCategoryIds);

        return $this->fetch();
    }

    /**
     * 编辑文章提交
     * @adminMenu(
     *     'name'   => '编辑文章提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑文章提交',
     *     'param'  => ''
     * )
     */
    public function editPost()
    {

        if ($this->request->isPost()) {
            $data   = $this->request->param();
            //需要抹除发布、置顶、推荐的修改。
            unset($data['post']['post_status']);
            unset($data['post']['is_top']);
            unset($data['post']['recommended']);
            $post = $data['post'];
            $data['catpost'] = isset($data['catpost']) ? $data['catpost'] : [];
            $catpost = $data['catpost'];
            $result = $this->validate($post, 'AdminArticle');
            if ($result !== true) {
                $this->error($result);
            }
            $row = Db::name('portal_category')->where("id",$post['categories'])->find();
            $field_where = [
                ["cat_id","like","%".$row['id']."%"],
                ['dtype',"like","img%"],
            ];
            $imgs = Db::name('channel_field')->where($field_where)->select();

            $row2 = Db::name('portal_category')->where("id=".$row['parent_id'])->find();
            $portalPostModel = new PortalPostModel();
            if (count($imgs)>0) {
                if (count($imgs) > 1) {

                    foreach ($imgs as $key => $value) {
                        if (isset($catpost[$value['name']])) {
                            if (is_array($catpost[$value['name']])) {
                                foreach ($catpost[$value['name']] as $k => $url) {
                                    $photoUrl = cmf_asset_relative_url($url);
                                    $catpost['s'][$value['name']][] = $photoUrl;
                                }
                                $data['catpost'][$value['name']] = json_encode($catpost['s'][$value['name']]);
                            }else{
                                $photoUrl = cmf_asset_relative_url($catpost[$value['name']]);
                                $data[$value['name']] = $photoUrl;
                            }
                            
                        }else{
                            $data['catpost'][$value['name']] = '';
                        }
                    }
                    
                }else{
                    if (isset($catpost[$imgs[0]['name']])) {
                        if (is_array($catpost[$imgs[0]['name']])) {
                            foreach ($catpost[$imgs[0]['name']] as $key => $url) {
                                $photoUrl = cmf_asset_relative_url($url);
                                $catpost[$imgs[0]['name']][$key] = $photoUrl;
                            }
                            $data['catpost'][$imgs[0]['name']] = json_encode($catpost[$imgs[0]['name']]);
                        }else{
                            $photoUrl = cmf_asset_relative_url($catpost[$imgs[0]['name']]);
                            $data['catpost'][$imgs[0]['name']] = $photoUrl;
                        }
                        
                    }else{
                        $data['catpost'][$imgs[0]['name']] = '';
                    }
                }
            }
            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }

            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $data['post']['more']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }

            if (!empty($row2)) {
               $data['post']['parent_id'] = $row2['id'];
            }
            $portalPostModel->adminEditArticle($data, $data['post']['categories']);

            $hookParam = [
                'is_add'  => false,
                'article' => $data['post']
            ];
            hook('portal_admin_after_save_article', $hookParam);

            $this->success('保存成功!');

        }
    }

    /**
     * 文章删除
     * @adminMenu(
     *     'name'   => '文章删除',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章删除',
     *     'param'  => ''
     * )
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function delete()
    {
        $param           = $this->request->param();
        $portalPostModel = new PortalPostModel();

        if (isset($param['id'])) {
            $id           = $this->request->param('id', 0, 'intval');
            $result       = $portalPostModel->where('id', $id)->find();
            $data         = [
                'object_id'   => $result['id'],
                'create_time' => time(),
                'table_name'  => 'portal_post',
                'name'        => $result['post_title'],
                'user_id'     => cmf_get_current_admin_id()
            ];
            $resultPortal = $portalPostModel
                ->where('id', $id)
                ->update(['delete_time' => time()]);
            if ($resultPortal) {
                PortalCategoryPostModel::where('post_id', $id)->update(['status' => 0]);
                PortalTagPostModel::where('post_id', $id)->update(['status' => 0]);

                RecycleBinModel::insert($data);
            }
            $this->success("删除成功！", '');

        }

        if (isset($param['ids'])) {
            $ids     = $this->request->param('ids/a');
            $recycle = $portalPostModel->where('id', 'in', $ids)->select();
            $result  = $portalPostModel->where('id', 'in', $ids)->update(['delete_time' => time()]);
            if ($result) {
                PortalCategoryPostModel::where('post_id', 'in', $ids)->update(['status' => 0]);
                PortalTagPostModel::where('post_id', 'in', $ids)->update(['status' => 0]);
                foreach ($recycle as $value) {
                    $data = [
                        'object_id'   => $value['id'],
                        'create_time' => time(),
                        'table_name'  => 'portal_post',
                        'name'        => $value['post_title'],
                        'user_id'     => cmf_get_current_admin_id()
                    ];
                    RecycleBinModel::insert($data);
                }
                $this->success("删除成功！", '');
            }
        }
    }

    /**
     * 文章发布
     * @adminMenu(
     *     'name'   => '文章发布',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章发布',
     *     'param'  => ''
     * )
     */
    public function publish()
    {
        $param           = $this->request->param();
        $portalPostModel = new PortalPostModel();

        if (isset($param['ids']) && isset($param["yes"])) {
            $ids = $this->request->param('ids/a');
            $portalPostModel->where('id', 'in', $ids)->update(['post_status' => 1, 'published_time' => time()]);
            $this->success("发布成功！", '');
        }

        if (isset($param['ids']) && isset($param["no"])) {
            $ids = $this->request->param('ids/a');
            $portalPostModel->where('id', 'in', $ids)->update(['post_status' => 0]);
            $this->success("取消发布成功！", '');
        }

    }

    /**
     * 文章置顶
     * @adminMenu(
     *     'name'   => '文章置顶',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章置顶',
     *     'param'  => ''
     * )
     */
    public function top()
    {
        $param           = $this->request->param();
        $portalPostModel = new PortalPostModel();

        if (isset($param['ids']) && isset($param["yes"])) {
            $ids = $this->request->param('ids/a');

            $portalPostModel->where('id', 'in', $ids)->update(['is_top' => 1]);

            $this->success("置顶成功！", '');

        }

        if (isset($_POST['ids']) && isset($param["no"])) {
            $ids = $this->request->param('ids/a');

            $portalPostModel->where('id', 'in', $ids)->update(['is_top' => 0]);

            $this->success("取消置顶成功！", '');
        }
    }

    /**
     * 文章推荐
     * @adminMenu(
     *     'name'   => '文章推荐',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章推荐',
     *     'param'  => ''
     * )
     */
    public function recommend()
    {
        $param           = $this->request->param();
        $portalPostModel = new PortalPostModel();

        if (isset($param['ids']) && isset($param["yes"])) {
            $ids = $this->request->param('ids/a');

            $portalPostModel->where('id', 'in', $ids)->update(['recommended' => 1]);

            $this->success("推荐成功！", '');

        }
        if (isset($param['ids']) && isset($param["no"])) {
            $ids = $this->request->param('ids/a');

            $portalPostModel->where('id', 'in', $ids)->update(['recommended' => 0]);

            $this->success("取消推荐成功！", '');

        }
    }

    /**
     * 文章排序
     * @adminMenu(
     *     'name'   => '文章排序',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章排序',
     *     'param'  => ''
     * )
     */
    public function listOrder()
    {
        parent::listOrders('portal_category_post');
        $this->success("排序更新成功！", '');
    }
}
